﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SharingCenter.Web.Classes.Posts
{
    [Serializable]
    public class ReadThreadEntry
    {
        Guid _threadId;
        string _threadTitle;
        DateTime _lastRead;

        public Guid ThreadId { get { return _threadId; } set { _threadId = value; } }
        public string ThreadTitle { get { return _threadTitle; } set { _threadTitle = value; } }
        public DateTime LastRead { get { return _lastRead; } set { _lastRead = value; } }

        public ReadThreadEntry(Guid threadId, string threadTitle, DateTime lastRead)
        {
            _threadId = threadId;
            _threadTitle = threadTitle;
        }

        public ReadThreadEntry() { }
    }

    [Serializable]
    public class ReadThreadEntryList
    {
        public List<ReadThreadEntry> _ReadThreadLsit;// = new List<ReadThreadEntry>();
        public ReadThreadEntryList() { _ReadThreadLsit = new List<ReadThreadEntry>(); }
        
        public void AddEntry(ReadThreadEntry entry)
        {
            if (_ReadThreadLsit == null) _ReadThreadLsit = new List<ReadThreadEntry>();
            var q = from t in _ReadThreadLsit
                    where t.ThreadId == entry.ThreadId
                    select t;
            if (q.Count() > 0)
            {
                _ReadThreadLsit.Remove(q.First());
            }

            _ReadThreadLsit.Add(entry);
        }

        public void RemoveEntry(Guid threadId)
        {
            if (_ReadThreadLsit == null) _ReadThreadLsit = new List<ReadThreadEntry>();
            _ReadThreadLsit.RemoveAll(d => d.ThreadId == threadId);
        }
        
        public List<ReadThreadEntry> ReadThreadLsit
        {
            get 
            {
                var q = from t in _ReadThreadLsit
                        orderby t.LastRead descending
                        select t;
                return q.ToList();
            }
        }

        //public DateTime ThreadRead;
        //public Dictionary<Guid, ReadThreadEntry> ReadThreadEntries = new Dictionary<Guid, ReadThreadEntry>();
    }

    public class ReadThreadOperations
    {
        public static void AddReadHistoryToProfile(ReadThreadEntry entry)
        {
            if (WebProfile.Current.Talks.ThreadReadHistory == null)
            {
                WebProfile.Current.Talks.ThreadReadHistory = new ReadThreadEntryList();
            }

            WebProfile.Current.Talks.ThreadReadHistory.AddEntry(entry);
            WebProfile.Current.Save();
        }
    }
}
